package howl.types.query;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import compiler.terminals.expression.Node;

import howl.model.PMF;
import howl.types.Datum;
import howl.types.Entry;
import howl.types.TableDescriptor;

public class QueryHelper {

	public static ResultSet query(Node l, String entityName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query1 = pm
				.newQuery("select from howl.types.TableDescriptor where Name == '"
						+ entityName
						+ "' "
						+ "import howl.types.TableDescriptor;");

		List<TableDescriptor> result1 = (List<TableDescriptor>) query1
				.execute();

		List<Datum> res = l.evaluate(result1.get(0).getId());

		Long[] arl = new Long[res.size()];
		for (int i = 0; i < res.size(); i++) {
			arl[i] = res.get(i).getParentID();
		}

		ResultSet rs = new ResultSet(arl);

		return rs;
	}

	public static ResultSet queryByEntity(String entityName, int maxReturn) {
		if (maxReturn > 999) {
			maxReturn = 999;
		}
		
		if(maxReturn ==0) {
			maxReturn = 1;
		}
		ArrayList<Long> res = new ArrayList<Long>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query td = pm.newQuery("select from howl.types.TableDescriptor "
				+ "where Name == Param " + "parameters String Param "
				+ "import howl.types.TableDescriptor;");

		List<TableDescriptor> result1 = (List<TableDescriptor>) td.execute(entityName);

		if (result1.size() >= 1) {
			Query en = pm
					.newQuery("select from howl.types.Entry where ParentID == PARAM import how.types.Entry;");
			en.declareParameters("Long PARAM");
			en.setOrdering("timestamp desc");

			List<Entry> entryResult = (List<Entry>) en.execute(result1.get(0)
					.getId());

			/*Query dt = pm
					.newQuery("select from howl.parser.types.Datum where ParentID == PARAM import how.parser.types.Datum;");
			dt.declareParameters("Long PARAM");*/

			if (entryResult.size() >= 1) {

				for (int i = 0; i < maxReturn && i < entryResult.size(); i++) {

					// List<Datum> dtresults =
					// (List<Datum>)dt.execute(entryResult.get(i).getId());
					res.add(entryResult.get(i).getId());
					/*
					 * for(int j = 0; j<dtresults.size();j++){
					 * res.add(dtresults.get(j).getId()); }
					 */

				}

				Long[] p = new Long[1];
				ResultSet r = new ResultSet(res.toArray(p));
				return r;
			} else {
				return new ResultSet();
			}
		}

		return new ResultSet();

	}


}
